package com.yndsoft.jc.widget;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Cool on 2017/8/9.
 */

public class AutoViewPager extends ViewPager {
    private Handler mHander = new Handler();


    private boolean startSwitch;

    public void setStartSwitch(boolean startSwitch) {
        this.startSwitch = startSwitch;
    }

    public AutoViewPager(Context context) {
        super(context);
    }

    public AutoViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                //停止轮播图的切换
                stopSwitch();

                break;
            case MotionEvent.ACTION_MOVE:

                stopSwitch();


                break;
            case MotionEvent.ACTION_UP:
                //开始切换
                startSwitch();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
    public void startSwitch() {
        if (!startSwitch) {//没有切换的时候才轮播
            mHander.postDelayed(new SwitchTask(), 3 * 1000);
        }
        startSwitch = true;
    }

    public void stopSwitch() {
        mHander.removeCallbacksAndMessages(null);
        startSwitch = false;
    }


    private class SwitchTask implements Runnable {
        @Override
        public void run() {

                int currentItem = getCurrentItem();
            if (getAdapter()==null){
                return;
            }
            if (currentItem == getAdapter().getCount() - 1) {//如果是最后一张图片
                currentItem = 0;//切换到第一张
            } else {
                currentItem++;
            }


            setCurrentItem(currentItem);//给图片设置新的索引
            mHander.postDelayed(this, 3 * 1000);//继续调用延时轮播的逻辑,实现自动轮播
        }
    }
}
